package com.jvm123.blog.service

import com.jvm123.blog.dao.UriAccessRuleRepos
import com.jvm123.blog.entity.UriAccessRule
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service

import javax.annotation.PostConstruct
import javax.servlet.http.HttpServletRequest

/**
 *
 * @author yawn http://jvm123.com
 *     2019/10/18 17:05
 */
@Service
class AccessServiceImpl implements AccessService {

    @Value('${access.skip-check}')
    boolean skipCheck

    @Autowired
    UriAccessRuleRepos uriAccessRuleRepos

    @Override
    String getRole(HttpServletRequest request) {
        null
    }

    @Override
    boolean checkRule(String uri, String role) {
        if (skipCheck) {
            return true
        }
        for(UriAccessRule rule : uriAccessRuleRepos.findAll().toSet()) {
            boolean access = rule.check(uri, role)
            if (access) {
                return true
            }
        }
        false
    }

    @PostConstruct
    def "初始化数据"() {
        UriAccessRule rule = new UriAccessRule(access: true,
                accessType: UriAccessRule.AccessType.FULL,
                pattern: "/admin/index.html")
        if (!uriAccessRuleRepos.findAll().contains(rule)) {
            uriAccessRuleRepos.save(rule)
        }
    }
}
